package com.yauchu.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.http.client.ClientProtocolException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

public class LatexImageLoader extends AsyncTask<String, Integer, Bitmap> {
	private ImageView iV;
	
	public LatexImageLoader(ImageView iV)
	{
		super();
		this.iV=iV;
	}
	@Override
	protected Bitmap doInBackground(String... params) {
		// TODO Auto-generated method stub
		
		try {
			//URI latex=new URL();
		
			URL url = new URL("http://www.codecogs.com/png.latex?"+URLEncoder.encode(params[0], "UTF-8"));
			URLConnection connection = url.openConnection();
			connection.setUseCaches(true);
			Object response = connection.getContent();
			if (response instanceof Bitmap) {
			  Bitmap bitmap = (Bitmap)response;
			  return bitmap;
			} else
			{
				if (response instanceof InputStream)
					{
						return BitmapFactory.decodeStream( (InputStream) response) ;
					}
				return null;
			}
        //HttpUrlConnection con= (HttpUrlConnection) latex.
        //DefaultHttpClient httpClient = new DefaultHttpClient();
        //HttpGet request = new HttpGet("http://www.codecogs.com/png.latex?"+URLEncoder.encode(params[0], "UTF-8"));
        //HttpResponse response = httpClient.execute(request);
        //return BitmapFactory.decodeStream( response.getEntity().getContent());
		
		
        	
			
        } catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	
	@Override
	public void onPostExecute(Bitmap result)
	{
		iV.setImageBitmap(result);
	}

}
